package com.hctforgreen.greenservice;

import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hctforgreen.greenservice.model.AttrEntity;
import com.hctforgreen.greenservice.model.BookListEntity.BookEntity;
import com.hctforgreen.greenservice.ui.adapter.FuzzySearchBooksListAdapter;
import com.hctforgreen.greenservice.ui.adapter.RecentStudyDataListAdapter;
import com.hctforgreen.greenservice.ui.adapter.RecentTerminalDataListAdapter;
import com.hctforgreen.greenservice.ui.handler.RecentStudyDataListHandler;
import com.hctforgreen.greenservice.ui.handler.RecentTerminalDataListHandler;
import com.hctforgreen.greenservice.ui.widget.LearningTypeListPopupView;
import com.hctforgreen.greenservice.utils.CheckDataVersionCodeUtil;
import com.hctforgreen.greenservice.utils.DownloadBookLstInitFinishUtil;
import com.hctforgreen.greenservice.utils.EntryCatalogUtil;
import com.hctforgreen.greenservice.utils.KeyboardUtil;

/**
 * 学习资料搜索页
 * 
 * @author dhb
 * 
 */
public class LearningActivity extends ParentActivity {
	/**
	 * 学习资料大类型
	 */
	private LearningTypeListPopupView mTypeListPopupView;
	private AttrEntity mCurrentFirstEntity;// 资料大类别
	/**
	 * 学习资料小类型
	 */
	private LearningTypeListPopupView mChildTypeListPopupView;
	private AttrEntity mCurrentSecondEntity;

	View convertView;
	/**
	 * 最近上传的学习资料
	 */
	private ListView recentListview;

	private LearningActivity mSelf;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_learning_materials);
		convertView = findViewById(R.id.lyt_parent);
		recentListview = (ListView) convertView.
				findViewById(R.id.lst_default_list);
		mSelf = this;
		initSkinLayout();
		initTitleButtonBar();
		initWindow();
		initClickEdgehide();

		updateBaseDataTips();

	}
	/**
	 * 2016-12-31 390694  检查基础数据包版本，提示去更新
	 */
	public void updateBaseDataTips() {
		CheckDataVersionCodeUtil checkDataVersionCodeUtil = new CheckDataVersionCodeUtil();

		checkDataVersionCodeUtil.new CheckDataVersionCodeTask(
				R.string.terminal_update_data_content,R.string.terminal_update_data_title, mSelf, true,
				null, null, null, null, null)
				.execute(mSelf);
	}

	/**
	 * 点击边缘隐藏
	 */
	private void initClickEdgehide() {
		LinearLayout parentLyt = (LinearLayout) findViewById(R.id.lyt_parent);
		parentLyt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setTopLayoutVisible();
				KeyboardUtil keyboardUtil = new KeyboardUtil();
				keyboardUtil.hideSoftKeyboard(v);
			}
		});
	}

	private boolean setTopLayoutVisible() {
		final LinearLayout topLyt = (LinearLayout) findViewById(R.id.lyt_top);
		if (topLyt.getVisibility() == View.GONE) {
			topLyt.setVisibility(View.VISIBLE);
			clearFocus();
			return true;
		}
		clearFocus();
		return false;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (setTopLayoutVisible()) {
				return true;
			}
			return super.onKeyDown(keyCode, event);
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	private void initTitleButtonBar() {
		final TextView titleTv = (TextView) findViewById(R.id.tv_title);
		titleTv.setText(getString(R.string.train_learning_materials));

		final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				KeyboardUtil keyboardUtil = new KeyboardUtil();
				keyboardUtil.hideSoftKeyboard(v);
				finish();
			}
		});
	}

	private void initWindow() {
		initLearningTypePopupView();
		initChildTypeListPopupView();
		initSearchBtn();

		initRecent();
	}
	/**
	 * 初始化最新上传资料列表
	 */
	private void initRecent() {
		RecentStudyDataListAdapter adapter;

		RecentStudyDataListHandler handler = new RecentStudyDataListHandler(
				this, convertView);
		adapter = new RecentStudyDataListAdapter(
				recentListview, this, R.layout.layout_loading,
				R.layout.layout_reloading, handler);
	}

	/**
	 * 初始化资料类别
	 */
	private void initLearningTypePopupView() {
		final Button seriesBooksBtn = (Button) findViewById(R.id.btn_series);
		seriesBooksBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showListPopupView(v);
			}

			private void initListPopupView() {
				mTypeListPopupView = new LearningTypeListPopupView(
						LearningActivity.this, mCurrentFirstEntity, mSelf, 0,
						null);

			}

			private void showListPopupView(View v) {
				initListPopupView();
				mTypeListPopupView.showAsDropDown(v);
			}
		});
	}

	private void initChildTypeListPopupView() {
		final Button seriesBooksBtn = (Button) findViewById(R.id.btn_child_series);
		seriesBooksBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showListPopupView(v);
			}

			private void initListPopupView() {
				if (mCurrentFirstEntity == null) {
					Toast.makeText(mSelf,
							getString(R.string.learning_materials_two_hint),
							Toast.LENGTH_LONG).show();
					return;
				}
				if (mChildTypeListPopupView == null) {
					mChildTypeListPopupView = new LearningTypeListPopupView(
							LearningActivity.this, mCurrentSecondEntity, mSelf,
							1, mCurrentFirstEntity.id);
				}

			}

			private void showListPopupView(View v) {
				initListPopupView();
				if (mChildTypeListPopupView != null) {
					mChildTypeListPopupView.showAsDropDown(v);
				}

			}
		});
	}

	// public void initSerieEntity(SerieEntity currentFirstEntity) {
	// mCurrentFirstEntity = currentFirstEntity;
	// }

	/**
	 * 小类别名称
	 */
	public void initChildTypeBtn(AttrEntity currentFirstEntity) {
		if (currentFirstEntity == null) {
			return;
		}
		final Button seriesBooksBtn = (Button) findViewById(R.id.btn_child_series);
		seriesBooksBtn.setText(currentFirstEntity.name);
	}

	public void initStudyTypeEntity(AttrEntity currentFirstEntity) {
		mCurrentFirstEntity = currentFirstEntity;
	}

	public void initStudyChildTypeEntity(AttrEntity currentSecondEntity) {
		mCurrentSecondEntity = currentSecondEntity;
	}

	public void initStudyTypeBtn(AttrEntity currentSecondEntity) {
		final Button childSeriesBooksBtn = (Button) findViewById(R.id.btn_series);
		childSeriesBooksBtn.setText(currentSecondEntity.name);
	}

	public void setFocusable(boolean bCanFocus) {
		// final EditText inputEt = (EditText) findViewById(R.id.et_input);
		// inputEt.setFocusable(bCanFocus);
		// inputEt.setFocusableInTouchMode(bCanFocus);
	}

	/**
	 * 清除小类别已选择值
	 */
	public void clearChildTypeBtn() {
		final Button childSeriesBooksBtn = (Button) findViewById(R.id.btn_child_series);
		childSeriesBooksBtn.setText("");
		mCurrentSecondEntity = null;
		mChildTypeListPopupView = null;
	}

	private void initFuzzySearchEt() {

		final LinearLayout topLyt = (LinearLayout) findViewById(R.id.lyt_top);
		final EditText inputEt = (EditText) findViewById(R.id.et_input);
		inputEt.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// if (!hasFocus) {
				// topLyt.setVisibility(View.VISIBLE);
				// } else if (hasFocus) {
				// if(!canDoFuzzySearch()){
				//
				// return;
				// }
				// topLyt.setVisibility(View.GONE);
				//
				// }

			}

			private boolean canDoFuzzySearch() {
				final Button childSeriesBooksBtn = (Button) findViewById(R.id.btn_child_series);
				if (!childSeriesBooksBtn.getText().equals("")) {
					return true;
				} else {
					return false;
				}
			}
		});

	}

	/**
	 * 初始化搜索框
	 */

	private void initSearchBtn() {
		final Button seriesBooksBtn = (Button) findViewById(R.id.btn_series);
		final EditText inputEt = (EditText) findViewById(R.id.et_input);
		final Button searchBtn = (Button) findViewById(R.id.btn_search);
		searchBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				/**
				 * 2016-12-31 390694 增加判断更新资料的服务是否在进行，是  则提示
				 */
				boolean isServiceRunning = DownloadBookLstInitFinishUtil.getUpdateBookServiceFinished(mSelf);
				if (isServiceRunning){
					Dialog dialog = null;
					AlertDialog.Builder builder = new AlertDialog.Builder(mSelf);
					builder.setTitle(R.string.dialog_default_title_hint)
							.setMessage(R.string.update_now)
							.setPositiveButton(R.string.dialog_confirm_hint,
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(DialogInterface dialog,
															int which) {
											dialog.dismiss();
										}
									});
					dialog = builder.create();
					dialog.show();
					return;
				}

				if (seriesBooksBtn.getText().toString().equals("")) {
					Intent intent = new Intent(LearningActivity.this,
					LearningListActivity.class);
					intent.putExtra("studyTypeId", "");
					String childtypeId = "";
					intent.putExtra("childtypeId", "");
					intent.putExtra("searchKey", inputEt.getText().toString());
					startActivity(intent);
				}else{
					setTopLayoutVisible();
					KeyboardUtil keyboardUtil = new KeyboardUtil();
					keyboardUtil.hideSoftKeyboard(v);
					// getDbBooksUseChildSeriesId(mCurrentFirstEntity,
					// mCurrentSecondEntity, inputEt.getText().toString()
					// .trim());

					Intent intent = new Intent(LearningActivity.this,
							LearningListActivity.class);
					intent.putExtra("studyTypeId", mCurrentFirstEntity.id);
					String childtypeId = mCurrentSecondEntity == null ? ""
							: mCurrentSecondEntity.id;
					intent.putExtra("childtypeId", childtypeId);
					intent.putExtra("searchKey", inputEt.getText().toString());
					startActivity(intent);
				}
				// if (childSeriesBooksBtn.getText().toString().equals("")) {
				// Toast.makeText(LearningActivity.this,
				// R.string.learning_materials_three_hint,
				// Toast.LENGTH_SHORT).show();
				// return;
				// }

			}
		});
	}

	/*
	 * private void fuzzySearchBookList(ChildSerieEntity currentSecondEntity,
	 * final String keyWord) { final View fuzzySearchLyt =
	 * findViewById(R.id.lyt_fuzzy_search); final LinearLayout emptyLyt =
	 * (LinearLayout) findViewById(R.id.lyt_default_list_empty);
	 * 
	 * fuzzySearchLyt.setVisibility(View.VISIBLE); if(keyWord.equals("")){
	 * if(currentSecondEntity != null && currentSecondEntity.dataList != null &&
	 * currentSecondEntity.dataList.size() > 0){
	 * emptyLyt.setVisibility(View.GONE);
	 * 
	 * initFuzzySearchLv(fuzzySearchLyt, currentSecondEntity.dataList); }else
	 * if(currentSecondEntity == null || currentSecondEntity.dataList == null ||
	 * currentSecondEntity.dataList.size() == 0){ //
	 * fuzzySearchLyt.setVisibility(View.GONE);
	 * emptyLyt.setVisibility(View.VISIBLE); }
	 * 
	 * }else if(!keyWord.equals("")){
	 * 
	 * List<BookEntity> bookList = null; for(BookEntity bean :
	 * currentSecondEntity.dataList){
	 * 
	 * if(bean.displayName.contains(keyWord)){
	 * 
	 * if(bookList == null){ bookList = new ArrayList<BookEntity>(); }
	 * bookList.add(bean); }
	 * 
	 * } if(bookList != null && bookList.size() > 0){
	 * emptyLyt.setVisibility(View.GONE); initFuzzySearchLv(fuzzySearchLyt,
	 * bookList); }else if(bookList == null || bookList.size() == 0){ //
	 * fuzzySearchLyt.setVisibility(View.GONE);
	 * emptyLyt.setVisibility(View.VISIBLE); }
	 * 
	 * }
	 * 
	 * }
	 */
	private void initFuzzySearchLv(final View fuzzySearchLyt,
			ListView fuzzySearchLV, final List<BookEntity> dataList) {

		new FuzzySearchBooksListAdapter(LearningActivity.this, fuzzySearchLV,
				dataList);

		fuzzySearchLV.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				final BookEntity entity = (BookEntity) dataList.get(position);
				EntryCatalogUtil catalogUtil = new EntryCatalogUtil();
				try {
					if (catalogUtil.startEntryCatalogActivity(
							LearningActivity.this, entity, true)) {
						setTopLayoutVisible();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});
	}

	private void clearFocus() {

		/**
		 * 使用EditText左侧的ImageView抢Focus
		 */
		View requestFocusTv = (View) findViewById(R.id.iv_request_focus);
		requestFocusTv.requestFocus();

		final EditText searchInputEt = (EditText) findViewById(R.id.et_input);
		searchInputEt.clearFocus();
	}

}
